/**
 * 图片审核
 * @returns {[[Type]]} [[Description]]
 */
define([
        '../../common/service',
        '../imageManage/picPreview',
        '../imageManage/comment'
    ],
    function(
        http,
        PicPreview,
        Comment
    ) {
        var Review = function() {};
        Review.prototype = $.extend(Review.prototype, {
            init: function() {
                    var _this = this;
                    _this.params = {
                        isReview: true
                    };
                    _this.initAppSelect(); //初始化应用
                    _this.initListManager(function(query) {
                        _this.params.pSize = query.pSize;
                        _this.queryImage();
                    });
                    _this.bindEvent();
                }
                /*
                    @绑定审核页面所需事件
                */
                ,
            bindEvent: function() {
                var _this = this;
                var adimageList = $('#adimage-review'), //列表 tbody
                    appSelect = $('#app-select'); //应用选择框 select

                //绑定打开审核详情界面事件
                adimageList.off('click', '.thumbnail-div');
                adimageList.on('click', '.thumbnail-div', function() {
                    _this.openImageModal(this.getAttribute('data-mid'));
                });
                //绑定列表项中审核事件
                adimageList.off('click', '.review-action');
                adimageList.on('click', '.review-action', function() {
                    var self = this;
                    var mid = self.getAttribute('data-mid');
                    $('#review-image-action').modal('show');
                    $('#review-image-action .btn-primary').off('click').on('click', function(e) {

                        var par = [{
                            mongodbId: self.getAttribute('data-mid'),
                            reviewStatus: 1
                        }]
                        var _reviewAction = $(self),
                            _icon = $('i', _reviewAction);
                        _icon.removeClass('fa-save');
                        _icon.addClass('fa-refresh get-loading-style3');

                        //在列表中 发送审核请求  _status_:请求成功与否, _reviewer_:审核人
                        _this.reviewForList(par, function(_status_, _reviewer_, _reviewTime_) {
                            //审核成功
                            if (_status_) {
                                var _nowTr = _reviewAction.parents('tr').eq(0);
                                _reviewAction.html('---');
                                $('td[revies-status]', _nowTr).html('人工审核通过');
                                $('td[revies-reviewer]', _nowTr).html(_reviewer_);
                                $('td[revies-reviewTime]', _nowTr).html(moment(_reviewTime_).format('YYYY/MM/DD HH:mm:ss'));
                                $('#review-image-action').modal('hide');
                                return;
                            }
                            _icon.removeClass('fa-refresh get-loading-style3');
                            _icon.addClass('fa-save');
                            $('#review-image-action').modal('hide');
                        });
                    });


                });
                //绑定列表项中评价事件
                adimageList.off('click', '.comment-action');
                adimageList.on('click', '.comment-action', function() {
                    var self = this;
                    new Comment(self.getAttribute('data-mid'));
                });
                //绑定图片左右移动
                var _openAdimageModal = $('#open-adimage-modal');
                _openAdimageModal.off('click', '.slider-action');
                _openAdimageModal.on('click', '.slider-action', function() {
                    var _sliderAction = $(this),
                        _mid = _openAdimageModal.attr('mid'),
                        _nowNode = $('div[data-mid="' + _mid + '"]').parents('tr').eq(0);

                    var _preNode = _nowNode.prev(),
                        _nextNode = _nowNode.next();
                    //向左 且 左有值
                    if (_sliderAction.hasClass('sa-left')) {
                        if (!_preNode || _preNode.length == 0) {
                            common.msgs.pop_up('以到最前一列数据', 'info');
                            return;
                        }
                        var _preMid = $('div[data-mid]', _preNode).attr('data-mid');
                        _this.openImageModal(_preMid);
                    }
                    //向右
                    else if (_sliderAction.hasClass('sa-right')) {
                        if (!_nextNode || _nextNode.length == 0) {
                            common.msgs.pop_up('以到最后一列数据', 'info');
                            return;
                        }
                        var _nextMid = $('div[data-mid]', _nextNode).attr('data-mid');
                        _this.openImageModal(_nextMid);
                    }

                });
            },
            getLocalTime: function(now) {
                    var year = now.getYear() + 1900;
                    var month = now.getMonth() + 1;
                    var date = now.getDate();
                    var hour = now.getHours();
                    var minute = now.getMinutes();
                    var second = now.getSeconds();
                    return year + "-" + month + "-" + date + "   " + hour + ":" + minute + ":" + second;
                }
                /*
                    @初始化列表管理
                */
                ,
            initListManager: function(cb) {
                    var _this = this;
                    var settings = {
                        setTopVal:193,//调整吸顶的高度,需要减去这个高度
                        scrollDOM:$('.fmp-article'),//监听滚动条
                        disableCache: false,
                        isDevelopMode: true,
                        supportAjaxPage: true, //是否支持配置列表ajxa分页[多列表两种状态都有时:统一配置项为true,禁用的列表项pageJson参数为空即可]

                        sortUpText: '1',
                        sortDownText: '-1',
                        sortingCallback: function(query) {
                            _this.params.sortList = [];
                            var defaultQuery = {
                                    mongodbId: 1
                                },
                                sortQuery = {};

                            for (prop in query) {
                                if (query[prop].length > 0) {
                                    sortQuery[prop] = query[prop];
                                }
                            }
                            if (sortQuery['pSize']) {
                                delete sortQuery['pSize'];
                            }

                            _this.params.sortList.push(sortQuery);
                            _this.params.sortList.push(defaultQuery);
                            _this.params.cPage = 1; //触发排序后 返回第一页
                            //  $.extend( _this.params, query);
                            _this.setPageCount();
                            _this.queryImage();
                        },
                        pageCallback: function(query) {
                            $.extend(_this.params, query);
                            _this.setPageCount();
                            _this.queryImage();
                        }
                    };
                    $('table[list-manager="adimage-review"]').listManager('init', settings, function(query) {
                        cb(query)
                    });
                }
                /*
                    @初始化应用列表
                */
                ,
            initAppSelect: function() {
                    var _this = this;
                    var appSelect = $('#app-select');
                    var par = {
                        typeId: 2 //1、主页; 2、应用
                    };
                    var loadingArea = appSelect.parents('.well').eq(0);
                    kit.loading.show(loadingArea);
                    http.do('/connectionobjects/searchConnectionObjectsByResourceManage', {
                        param: JSON.stringify(par)
                    }, 'POST').then(function(result) {
                        kit.loading.hide(loadingArea);
                        if (result.flag == 'fail') {
                            kit.alert2(result.msg);
                            return;
                        }

                        var data = result.data;


                        data = _.sortBy(data, function(item) {
                            return item.name.toLowerCase();
                        });
                        var tmpHtml = '<option value="">' + I18N.getText('imageReview', 'plsSelectApp') + '</option>';
                        for (var i = 0; i < data.length; i++) {
                            tmpHtml += '<option value="' + (data[i].name || '') + '">' + data[i].name + '</option>';
                        }
                        appSelect.html(tmpHtml);
                        appSelect.select2().on('change', function(query) {
                            if ($(this).val()) {
                                _this.params.appNames = [$(this).val()];
                            } else {
                                delete(_this.params.appNames);
                            }
                            _this.params.cPage = 1;
                            _this.queryImage();
                        });
                    }, function(msg, data, type, errorCode) {
                        kit.loading.hide(loadingArea);
                        kit.alert2('获取列表失败！');
                    });

                }
                /*
                    @查询图片
                */
                ,
            queryImage: function() {
                    var _this = this;
                    var loadingArea = $('#adimage-manager-page');
                    kit.loading.show(loadingArea);
                    http.do('/adresource/getReviewAdimageList', {
                        param: JSON.stringify(_this.params)
                    }, 'POST').then(function(result) {
                        kit.loading.hide(loadingArea);
                        if (result.flag == 'fail') {
                            kit.alert2(result.msg);
                            return;
                        }
                        var data = result.data;
                        _this.params.tSize =  data.summary?( data.summary.totalCount?data.summary.totalCount:0):0;
                        _this.setPageCount();
                        var _adimageRow = $('#adimage-row'),
                            _table =
                            $('table[list-manager="adimage-review"]', _adimageRow),
                            _adimageList = $('#adimage-review', _table);

                        _adimageList.html(_this.createImagesHtml(data.resources));
                        _table.listManager([{
                            'resetTd': false
                        }]);
                        $('.review-status-message').popover({
                            content: function() {
                                var content = $(this).data("popcontent");
                                return window.decodeURI(content);
                            }
                        })
                    }, function(msg, data, type, errorCode) {
                        kit.loading.hide(loadingArea);
                    });

                }
                /*
                    @配置分页数据
                */
                ,
            setPageCount: function() {
                    var _this = this;
                    var tSize = _this.params.tSize,
                        pSize = _this.params.pSize || $('select[name="pSizeArea"]').val() || 10;
                    var paginator = {
                        tSize: tSize,
                        pSize: pSize,
                        tPage: Math.ceil(tSize / pSize),
                        cPage: _this.params.cPage || 1
                    };
                    $('table[list-manager="adimage-review"]').listManager('resetPageData', paginator);
                }
                /*
                    @生成素材列表HTML
                    $.resources: 生成列表所需数据
                    ^.tmpHtml: 生成列表HTML片段
                */
                ,
            createImagesHtml: function(resources) {
                    var _this = this;
                    var tmpHtml = '',
                        reviewActionHtml = '';
                    if (!resources || resources.length === 0) {
                        return tmpHtml;
                    }
                    //定义操作栏 评价

                    $.each(resources, function(i, v) {
                        var popcontent = v.adReviewFeedback ? v.adReviewFeedback.replace(/\"/g, "&quot;") : 'unkown!can not passed!';
                        popcontent = window.encodeURI(popcontent);
                        var popoverHtml = v.reviewStatus == 6 ? '<a href="javascript:void(0);" class="review-status-message"  data-toggle="popover" data-trigger="hover" data-placement="left" data-popcontent="' + popcontent + '"> <i class="fa fa-exclamation-triangle"></i></a>' : '';
                        reviewActionHtml = v.reviewStatus != 5 ?
                            '---' : '<span class="review-action" data-mid="' + v.mongodbId + '"><i class="fa fa-save icon-btn"></i><span>' + I18N.getText('imageReview', 'review') + '</span></span>';
                        var reviewStatusStr;

                        var commentHtml = '<span class="comment-action" data-mid="' + v.mongodbId + '"><i class="fa fa-comment-o icon-btn"></i><span>' + I18N.getText('imageReview', 'comment') + '</span></span>';
                        if (v.reviewStatus) {
                            switch (Number(v.reviewStatus)) {
                                case 0:
                                    reviewStatusStr = I18N.getText('imageReview', 'machinesToBeAudited');
                                    break;
                                case 1:
                                    reviewStatusStr = I18N.getText('imageReview', 'byManualReview');
                                    break;
                                case 2:
                                    reviewStatusStr = I18N.getText('imageReview', 'notByManualReview');
                                    break;
                                case 4:
                                    reviewStatusStr = I18N.getText('imageReview', 'machineAudit');
                                    break;
                                case 5:
                                    reviewStatusStr = I18N.getText('imageReview', 'pendingManualReview');
                                    break;
                                case 6:
                                    reviewStatusStr = I18N.getText('imageReview', 'theMachineDoesNotPassTheAudit');
                                    break;
                                default:
                                    reviewStatusStr = "";
                            }
                        } else {
                            reviewStatusStr = "";
                        }
                        tmpHtml += '<tr class="adimage-data">' + '<td><div class="thumbnail-div slider-action" data-mid="' + v.mongodbId + '"><img src="' + v.litImgURL + '"></div></td>' + '<td>' + moment(new Date(v.createTime)).format('YYYY/MM/DD HH:mm:ss') + '</td>' + '<td revies-status="' + v.mongodbId + '">' + reviewStatusStr + popoverHtml + '</td>' + '<td>' + (v.uploadUserName || '--') + '</td>' + '<td revies-reviewer="' + v.mongodbId + '">' + (typeof(v.reviewer) == "undefined" ? ' ' : v.reviewer) + '</td>' + '<td revies-reviewTime="' + v.mongodbId + '">' + (typeof(v.reviewTime) == "undefined" ? ' ' : moment(new Date(v.reviewTime)).format('YYYY/MM/DD HH:mm:ss')) + '</td>' + '<td>' + reviewActionHtml + '&nbsp;&nbsp;|&nbsp;&nbsp;' + commentHtml + '</td>' + '</tr>'
                    });
                    return tmpHtml;
                }
                /*
                    @打开图片详情
                    $._mid_: 图片ID
                */
                ,
            openImageModal: function(_mid_) {
                    var picPreview = new PicPreview(_mid_);
                }
                /*
                    @列表中直接审核 提交数据
                    $._adimageArr_: 审核所需要数据
                    $.cb:回调
                */
                ,
            reviewForList: function(_adimageArr_, cb) {
                var _this = this;

                _this.showLoading();
                http.do('/adresource/saveImgTags', {
                    param: JSON.stringify(_adimageArr_)
                }, 'POST').then(function(result) {
                    _this.hideLoading();
                    if (result.flag == 'fail') {
                        kit.alert2(result.msg);
                        return;
                    }
                    typeof(cb) == 'function' ? cb(true, result.data.results[0].reviewer, result.data.results[0].reviewTime): '';
                }, function(msg, data, type, errorCode) {
                    _this.hideLoading();
                    common.msgs.pop_up(msg || 'fail!', 'error');
                    typeof(cb) == 'function' ? cb(false): '';
                });
            },
            dispose: function() {

            },
            /**
             * [adjustHeight 调整高度]
             * @return {[type]} [description]
             */
            adjustHeight: function() {
                var container = $('body,html');
                container.animate({
                    scrollTop: 100
                });
                var height = $('#adimage-manager-page').height();
                $('body').css('min-height', height + 'px')
            },
            showLoading: function($dom) {
                var self = this;
                var loadingArea = $dom ? $dom : $('#widget-grid');
                kit.loading.show(loadingArea);
            },
            hideLoading: function($dom) {
                var self = this;
                var loadingArea = $dom ? $dom : $('#widget-grid');
                kit.loading.hide(loadingArea);
            },
        });

        return new Review();
    });
